package com.elitetyc.eliteim.common.handler.impl;

import cn.hutool.core.lang.ParameterizedTypeImpl;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.TypeUtil;
import cn.hutool.json.JSONUtil;
import com.elitetyc.eliteim.common.proto.RequestProto;
import com.elitetyc.eliteim.common.handler.RequestMsgHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author yuanchao.tan
 * @version 1.0
 * @description 将消息内容转换为指定的泛型类型
 * @Date 2021/9/16 14:18
 */
public abstract class BaseMsgHandler<T> implements RequestMsgHandler<T> {

    @Override
    public T convertProto2Msg(RequestProto.RequestProtocol source) {
        final ParameterizedType parameterizedType = TypeUtil.toParameterizedType(this.getClass());
        final Type actualTypeArgument = parameterizedType.getActualTypeArguments()[0];
        if (actualTypeArgument instanceof Class){
            Class<?> aClass = (Class<?>) actualTypeArgument;
            return (T) JSONUtil.toBean(source.getData(), aClass);
        }else {
            Class<?> aClass = (Class<?>)TypeUtil.toParameterizedType(actualTypeArgument).getActualTypeArguments()[0];
            return (T) JSONUtil.toList(source.getData(), aClass);
        }
    }
}
